package com.wang.springframework.beans.factory.support;

import com.wang.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * @author wangjianhua
 * @Description cglib实例化bean
 * @date 2021/8/23/023 15:59
 **/
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy{


    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor<?> ctor, Object[] args) {
        Enhancer enhancer = new Enhancer();
        //设置cglib代理类 生成子类
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        //无参构造器
        if(null == ctor){
            return enhancer.create();
        }
        //有参构造器 真正的有参构造器还需要比较类型与参数是否符合 这里简单实现一下
        return enhancer.create(ctor.getParameterTypes(),args);
    }
}
